<?php
namespace mobile\libs;

class Request{
	/**
	 * 复合请求
	 */
	public static function run($data) {
		if( isset($data['match']) ) {
			!isset($data['main']['cookie']) && $data['main']['cookie'] = true;
			self::match($data);
		}
		
		if( isset($data['list']) ) {
			!isset($data['main']['cookie']) && $data['main']['cookie'] = true;
			
			foreach($data['list'] as $item) {
				!isset($item['referer']) && $item['referer'] = @ $data['main']['referer'];
				$item['cookie'] = @ $data['main']['cookie'];
				
				self::normalRequest($item);
			}
		}
		
		return self::normalRequest($data['main']);
	}
	
	/**
	 * 根据正则，匹配内容，并替换
	 */
	public static function match(&$data) {
		$match = $data['match'];
		$match['cookie'] = @ $data['main']['cookie'];
		!isset($match['referer']) && $match['referer'] = @ $data['main']['referer'];
		
		$model = Replacer::model();
		
		$match['url'] = $model->replace($match['url']);
		$match['data'] = $model->replace($match['data']);
		
		$attributes = Helper::matchAttributes($match);
		
		if(isset($data['list'])) {
			foreach($data['list'] as &$item) {
				$item['url'] = $model->replaceAttributes($item['url'], $attributes);
				$item['data'] = $model->replaceAttributes($item['data'], $attributes);
			}
			unset($item);
		}
		
		$data['main']['url'] = $model->replaceAttributes($data['main']['url'], $attributes);
		$data['main']['data'] = $model->replaceAttributes($data['main']['data'], $attributes);
		
		if(isset($data['main']['http_header'])) {
			foreach($data['main']['http_header'] as &$item) {
				$item = $model->replaceAttributes($item, $attributes);
			}
		}
	}
	
	/**
	 * 普通请求
	 */
	public static function normalRequest($data) {
		$requestData = Replacer::model()->replace($data['data']);
		$url = Replacer::model()->replace($data['url']);
		
		// 有需要处理的参数
		if(isset($data['process'])) {
			!empty($requestData) && $requestData .= '&';
			
			foreach($data['process'] as $key => $item) {
				$requestData .= sprintf('%s=%s&', $key, call_user_func_array($item[0], $item[1]));
			}
			$requestData = substr($requestData, 0, -1);
			unset($data['process']);
		}
		
		$res = self::sendRequest($url, $requestData, $data);
		
		return $res;
	}
	
	/**
	 * 发送请求
	 */
	public static function sendRequest($url, $data, $params = array()) {
		$params = array_merge(array(
			'post'=>false,
			'referer'=>'',
			'cookie'=> false,
			'ssl_verifypeer'=>false,
			'timeout'=>5
		), $params);
		
		$params['post'] ? $params['data'] = $data : $url .= '?'.$data;
		
		// 从URL 自动匹配 referer
		if(empty($params['referer'])) {
			$urlData = parse_url($url);
			$params['referer'] = $urlData['scheme'].'://'.$urlData['host'];
		}
		
		$curl = Curl::model();
		
		$result = $curl->request($url, $params);
		return trim($result);
	}
}